<?php 
namespace app\common\model;
class Cartype extends Common{
	protected $insert = ['addtime'=>SYS_TIME,'depth'];
	protected function getPnameAttr($value,$data){
		return $data['pid'] ? $this->where("id",$data['pid'])->value("title") : '顶级分类';
	}
	protected function getThumbAttr($value){
		if(strpos($value,"http://") !== false){
			return $value;
		}
		else{
			return $value ? rtrim(APP_URL,"/").'/'.$value : '';
		}
	}
	protected function getAlldataAttr($value, $data){
		$arr = [0=>'显示',1=>'隐藏'];
		$data['hidename'] = $arr[$data['hide']];
		$data['recom'] = $data['isrecom'] ? '是' : '否';
		$data['pname'] = $data['pid'] ? $this->where("id",$data['pid'])->value("title") : '顶级分类';
		return $data;
	}
	protected function setDepthAttr($value, $data){
		if ($data['pid'] == 0) {
			return 1;
		}
		$pdepth = $this->where('id', $data['pid'])->value('depth');
		return $pdepth + 1;
	}
	public function get_list($searchData=[],$whereData=[],$limit = 0,$offset = 0, $order=''){
		$id = isset($whereData['pid']) ? $whereData['pid'] : 0;
		$db = model("Cartype");
		if ($id) {
			$info = $this->get_data(['item_id'=>$id]);
			if ($info['depth'] == 3) {
				$db = model("Car");
			}
		}
		$where = get_map($searchData,$whereData);
        $whereOr = get_or($searchData);
     	if (!$order) {
			$pk = $this->getPk();
			$order = "$pk asc";
		}
        $list = $db->where($where)->where('hide', 0)->whereOr($whereOr)->limit($offset,$limit)->order($order)->select();
        $lists = [];
        foreach ($list as $v) {
        	$data = $v['alldata'];
        	$lists[] = $data;
        }
        trace($lists);
        return [$lists,$where];

	}
	public function set_hide($id, $hide=0){
		$ids = $this->where('id', $id)->setField('hide', $hide);
		$list = $this->where('pid', $id)->order('id asc')->select();
		if (empty($list)) {
			return $ids;
		}
		foreach ($list as $v) {
			if ($v['depth'] == 3) {
				model("Car")->where('pid', $v['id'])->setField('hide', $hide);
			}
			$this->set_hide($v['id'], $hide);
		}
		return true;
	}
	public function delete_all($ids){
		$carpids = [];
		while ($ids) {
			$list = $this->where('pid', 'in', $ids)->order('id desc')->select();
			$info = [];
			foreach ($list as $v) {
				$info[] = $v['id'];
			}
			$this->delete_data(['item_ids'=>$ids]);
			if (empty($info)) {
				$carpids = $ids;
				break;
				$ids = '';
			}else{
				$ids = implode(',', $info);
			}
		}
		$lists = model('Car')->where('pid', 'in', $carpids)->select();
		$infoo = [];
		foreach ($lists as $v) {
			$infoo[] = $v['id'];
		}
		model('Car')->where('pid', 'in', $carpids)->delete();
		return model('CarData')->where('id', 'in', $infoo)->delete();
	}
}